package com.mrx.example.util;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.logging.log4j.core.config.builder.api.AppenderComponentBuilder;
import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilder;
import org.apache.logging.log4j.core.config.builder.api.LayoutComponentBuilder;
import org.apache.logging.log4j.core.config.builder.api.RootLoggerComponentBuilder;
import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration;

/**
 * 使用代码配置 Log4j2
 */
public class XLog {

    private XLog() {
    }

    static {
        ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationFactory.newConfigurationBuilder();
        AppenderComponentBuilder console = builder.newAppender("stdout", "Console");
        LayoutComponentBuilder std = builder.newLayout("PatternLayout");
        std.addAttribute("pattern", "%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %logger{36} %-5level: %msg%n%throwable");
        console.add(std);
        builder.add(console);
        RootLoggerComponentBuilder root = builder.newRootLogger(Level.DEBUG);
        root.add(builder.newAppenderRef("stdout"));
        builder.add(root);
        Configurator.initialize(builder.build());
    }

    public static Logger getLogger(String name) {
        return LogManager.getLogger(name);
    }

    public static Logger getLogger(Class<?> clazz) {
        return LogManager.getLogger(clazz.getName());
    }

}
